/**
 * Created by LMN on 2016/7/14.
 */
var io= require('socket.io');
var cache = {};

module.exports = {
    /**
     * Socket.io server listen on the port of HTTP server.
     * @param server , HTTP server.
     */
    listen: function(server){
        //io is the Socket.io server object.
        io = io.listen(server);
        /**
         * Event, when Socket.io client connect to this server.
         * @param socket , the socket object of this connection.
         */
        io.sockets.on('connection', function(socket){
            /**
             * Event, when client send user's information.
             * @param data , the data object which client sent.
             */
            socket.on('login',function(data){
                //Save user's socket object.
                socket._username = data.username+'';
                if(cache.hasOwnProperty(data.username+'')){
                    cache[data.username+''][socket.id] = socket;
                }else{
                    cache[data.username+''] = {};
                    cache[data.username+''][socket.id] = socket;
                }
            });
            /**
             * Event, when client send disconnect request.
             */
            socket.on('dis', function () {
                socket.disconnect();
            });
            /**
             * Event, when connection is disconnected.
             */
            socket.on('disconnect',function(){
                //Delete user's socket object.
                if(socket.id&&socket._username&&cache.hasOwnProperty(socket._username)&&cache[socket._username].hasOwnProperty(socket.id))
                    delete cache[socket._username][socket.id];
            });
        });
    },
    /**
     * Send object to an user.
     * @param username , the user's login name.
     * @param url , one of the message url in the client.
     * @param msg , the object need to be sent.
     */
    send: function(username, url, msg){
        if(cache.hasOwnProperty(username+'')){
            //Look for all the socket object of this user.
            for(var id in cache[username+'']){
                cache[username+''][id].emit(url, msg);
                if(url=='kickout'){
                    cache[username+''][id].disconnect()
                }
            }
        }
    }
};